package com.api.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.api.mapper.BuildingMapper;
import com.api.mapper.ChamberMapper;
import com.api.mapper.UserMapper;
import com.api.pojo.User;
import com.api.utils.Time;
import com.api.utils.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserMapper um;

    @Autowired
    BuildingMapper bm;

    @Autowired
    ChamberMapper cm;

    @Value("${root}")
    public String root;

    @Value("${ip}")
    public String ip;

    // 登录
    @PostMapping("/login")
    public Map<String, Object> login(User user) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        User userInfo = um.getByAccountRole(user);
        if (userInfo == null) {
            code = 500;
            msg = "账号不存在";
        } else if (!userInfo.getPassword().equals(Tool.getMD5(user.getAccount() + user.getPassword()))) {
            code = 501;
            msg = "密码错误";
        } else {
            user.setPassword(null);
            map.put("data", userInfo);
        }

        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    // 创建
    @PostMapping("/create")
    public Map<String, Object> create(User user) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        user.setPassword(Tool.getMD5(user.getAccount() + user.getPassword()));
        um.create(user);
        map.put("data", true);

        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    // 修改
    @PutMapping("/update")
    public Map<String, Object> update(User user) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        um.update(user);
        map.put("data", true);

        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    // 删除
    @DeleteMapping("/remove")
    public Map<String, Object> remove(Integer id) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        um.remove(id);
        map.put("data", true);

        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    // 查询
    @GetMapping("/get")
    public Map<String, Object> get(Integer role, Integer pageNo, Integer pageSize, String nickname) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        List<User> list;
        Integer total;
        pageNo = --pageNo * pageSize;
        if (nickname == null) {
            list = um.get(role, pageNo, pageSize);
            total = um.count(role);
        } else {
            nickname = "%" + nickname + "%";
            list = um.getByNickname(role, pageNo, pageSize, nickname);
            total = um.countByNickname(role, nickname);
        }

        if (role > 0) {
            list.forEach(e -> {
                e.setBuilding(bm.getById(e.getBid()));
                e.setChamber(cm.getById(e.getCid()));
            });
        }

        map.put("code", code);
        map.put("msg", msg);
        map.put("data", list);
        map.put("total", total);
        return map;
    }

    // 获取用户信息
    @GetMapping("/getInfo")
    public Map<String, Object> getInfo(Integer id) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        User user = um.getById(id);
        user.setPassword(null);
        if (user.getRole() == 2) {
            user.setBuilding(bm.getById(user.getBid()));
            user.setChamber(cm.getById(user.getCid()));
        }
        map.put("data", user);
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    // 修改密码
    @PutMapping("/updatePassword")
    public Map<String, Object> updatePassword(Integer id, String password, String newPassword) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        User user = um.getById(id);
        if (user == null) {
            code = 500;
            msg = "用户不存在";
        } else if (!user.getPassword().equals(Tool.getMD5(user.getAccount() + password))) {
            code = 501;
            msg = "旧密码错误";
        } else um.updatePassword(id, Tool.getMD5(user.getAccount() + newPassword));
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    // 重置密码
    @PutMapping("/resettingPassword")
    public Map<String, Object> resettingPassword(Integer id) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        User user = um.getById(id);
        if (user == null) {
            code = 500;
            msg = "用户不存在";
        } else {
            user.setPassword(Tool.getMD5(user.getAccount() + user.getAccount()));
            um.updatePassword(id, user.getPassword());
        }
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }
    
    // 导出数据
    @GetMapping("/reader")
    public Map<String, Object> reader(Integer role) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";
        String dir = "excel/userData-" + Time.getStamp() + ".xls";

        ExcelWriter writer = ExcelUtil.getWriter(root + dir);
        List<Map<String, Object>> data = new ArrayList<>();
        String[] roles = {"管理员", "宿管员", "学生"};
        String[] states = {"正常", "迁出"};
        for (User user : um.getAll(role)) {
            Map<String, Object> item = new LinkedHashMap<>();
            item.put("ID", user.getId());
            item.put("姓名", user.getNickname());
            item.put("账号", user.getAccount());
            item.put("性别", user.getGender());
            item.put("联系电话", user.getPhone());
            item.put("角色", roles[user.getRole()]);
            item.put("状态", states[user.getState()]);
            if (role == 2) {
                user.setBuilding(bm.getById(user.getBid()));
                user.setChamber(cm.getById(user.getCid()));
                item.put("楼号", user.getBuilding().getLabel());
                item.put("寝室号", user.getChamber().getLabel());
            }
            item.put("创建时间", user.getTime());
            data.add(item);
        }
        writer.write(data, true);
        writer.close();

        map.put("data", ip + dir);
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    // 导入数据
    @PostMapping("/writer")
    public Map<String, Object> writer(String url) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        url = url.replace(ip, root);
        ExcelReader reader = ExcelUtil.getReader(url);
        reader.addHeaderAlias("姓名","nickname");
        reader.addHeaderAlias("账号","account");
        reader.addHeaderAlias("密码","password");
        reader.addHeaderAlias("角色","role");
        reader.addHeaderAlias("性别","gender");
        reader.addHeaderAlias("楼号","bid");
        reader.addHeaderAlias("寝室号","cid");
        reader.addHeaderAlias("手机号","phone");
        List<User> userList = reader.readAll(User.class);
        for (User user : userList) {
            user.setPassword(Tool.getMD5(user.getAccount() + user.getPassword()));
            if (um.getByAccountRole(user) == null) um.create(user);
            else {
                code = 500;
                msg = "账号：" + user.getAccount() + "; 角色：" + user.getRole() + "已存在";
            }
        }

        map.put("code", code);
        map.put("msg", msg);
        return map;
    }
}
